package com.xxx.service.handler;

import com.xxx.common.constant.MessageConstant;
import com.xxx.common.exception.AccountNotFoundException;
import com.xxx.common.exception.BaseException;
import com.xxx.common.exception.PermissionDeniedException;
import com.xxx.common.exception.ResourceNotFoundException;
import com.xxx.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 * 遵循HTTP状态码规范处理异常
 */
@RestControllerAdvice(basePackages = {"com.ms.controller.admin", "com.ms.controller.user"}) // 处理所有控制器
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("未处理的异常: ", e);
        return Result.error(500, MessageConstant.UNKNOWN_ERROR);
    }
    
    /**
     * 捕获业务异常
     * @param ex 业务异常
     * @return 错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("业务异常：{}", ex.getMessage());
        return Result.error(400, ex.getMessage());
    }

    /**
     * 捕获资源未找到异常
     * @param ex 资源未找到异常
     * @return 404错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(ResourceNotFoundException ex){
        log.error("资源未找到：{}", ex.getMessage());
        return Result.notFound(ex.getMessage());
    }
    
    /**
     * 捕获权限拒绝异常
     * @param ex 权限拒绝异常
     * @return 403错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(PermissionDeniedException ex){
        log.error("权限不足：{}", ex.getMessage());
        return Result.forbidden(ex.getMessage());
    }
    
    /**
     * 捕获账号未找到异常
     * @param ex 账号未找到异常
     * @return 404错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(AccountNotFoundException ex){
        log.error("账号未找到：{}", ex.getMessage());
        return Result.notFound(ex.getMessage());
    }

    /**
     * 捕获SQL运行时异常
     * @param ex SQL完整性约束异常
     * @return 对应的错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        // Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            return Result.badRequest("账号：" + username + "已存在");
        } else {
            return Result.error(500, MessageConstant.OPERATION_FAILED);
        }
    }
    
    /**
     * 捕获数据库访问异常
     * @param ex 数据库访问异常
     * @return 服务器错误响应
     */
    @ExceptionHandler
    public Result exceptionHandler(DataAccessException ex) {
        log.error("数据库访问异常：", ex);
        return Result.error(500, MessageConstant.OPERATION_FAILED);
    }
}